import axios from 'axios'
import io from 'socket.io-client'
const socket = io('ws://localhost:9093')

// 聊天列表
const MSG_LIST = 'MSG_LIST'
// 读取信息
const MSG_RECV = 'MSG_RECV'
// 标识已读
const MSG_READ = 'MSG_READ'

const initState = {
  chatmsg: [],
  users: {},
  unread: 0
}

/**
 * reducers
 * @param {*} state 
 * @param {*} action 
 * @returns 
 */
export function chat(state = initState, action) {
  switch (action.type) {
    case MSG_LIST:
      return { ...state,
        users: action.payload.users,
        chatmsg: action.payload.msgs,
        unread: action.payload.msgs.filter(v => !v.read && v.to === action.payload.userid).length 
      }
    case MSG_RECV:
      // 消息中的 to 属性，是否和当前登录的用户 id 相同
      // 如果是，则这条消息就是给当前这个用户的，那么未读数量 + 1
      const n = action.payload.to === action.userid ? 1 : 0
      return {
        ...state,
        chatmsg: [...state.chatmsg, action.payload],
        unread: state.unread + n
      }
    case MSG_READ:
      // 发送方 ID
      const { from } = action.payload
      return {
        ...state, 
        chatmsg: state.chatmsg.map(v => ({...v, read: from === v.from ? true : v.read})),
        unread: state.unread.num ? state.unread.num : 0}
    default:
      return state
  }
}

function msgRecv(msg, userid) {
  return { userid, type: MSG_RECV, payload: msg }
}

/**
 * 监听广播
 */
export function recvMsg() {
  return (dispatch, getState) => {
    // 监听广播
    socket.on('recvmsg', function(data) {
      const userid = getState().user._id
      // userid => 当前登录用户的 ID
      dispatch(msgRecv(data, userid))
    })
  }
}

function msgList(msgs, users, userid) {
  return { type: MSG_LIST, payload: {msgs, users, userid} }
}

/**
 * 获取消息列表
 */
export function getMsgList() {
  return (dispatch, getState) => {
    axios.get('/user/getmsglist').then(res => {
      // msgs => 所有的消息列表
      // users => 所有的用户
      if (res.status === 200 && res.data.code === 0) {
        const userid = getState().user._id
        // userid => 当前登录用户的 ID
        dispatch(msgList(res.data.msgs, res.data.users, userid))
      }
    })
  }
}

/**
 * 发送消息
 * @param {*} from 发送者, to 接收者
 * 
 */
export function sendMsg({ from, to, msg }) {
  return () => {
    socket.emit('sendmsg', { from, to, msg })
  }
}

function msgRead({ from, userid, num }) {
  return { type: MSG_READ, payload: { from, userid, num } }
}

/**
 * 读消息
 * @param {发送方 ID} from 
 * @returns 
 */
export function readMsg(from) {
  return (dispatch, getState) => {
    axios.post('/user/readmsg', {from}).then(res => {
      const userid = getState().user._id
      if (res.status === 200 && res.data.code === 0) {
        const num = res.data.num
        dispatch(msgRead({ userid, from, num }))
      }
    })
  }
}
